/*
 * Copyright (C) 2010 Rodion Volkov (volkov.rodion@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rchik.divermate;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout.LayoutParams;

import com.rchik.divermate.DiveTablesDBAdapter.DataNotPresentException;
import com.rchik.divermate.NumberPicker.OnChangedListener;
import com.rchik.divermate.NumberPicker.OnMetricChangedListener;

public class TimeToRestBeforeDiveActivity extends Activity implements OnClickListener, OnChangedListener, OnMetricChangedListener, OnCheckedChangeListener, OnTouchListener {

	private int depth;
	private int time;
	private NumberPicker depthNumberPicker;
	private NumberPicker timeNumberPicker;
	
	private SharedPreferences prefs;
	private static final PopupWindow[] popupWindowArray = new PopupWindow[1];
	
	private View topLayout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dive_depth_time);
		
		topLayout = this.findViewById(R.id.TopLayout);
		
		ImageButton button = (ImageButton)findViewById(R.id.DiveButton);
		button.setOnClickListener(this);
		button.setImageResource(R.drawable.calculate_button_image);
		button = (ImageButton)findViewById(R.id.CancelDiveButton);
		button.setOnClickListener(this);
		depthNumberPicker = ((NumberPicker)findViewById(R.id.Depth));
		timeNumberPicker = ((NumberPicker)findViewById(R.id.Time));
		
		depthNumberPicker.Initialize();
		timeNumberPicker.Initialize();
		
		depthNumberPicker.setMetricTypes(DivingMenu.getMetricTypes());
		depthNumberPicker.selectMetricType(DivingMenu.getSelectedMetricType());
		
		depthNumberPicker.setOnMetricChangeListener(this);
		
		depthNumberPicker.setOnChangeListener(this);
		timeNumberPicker.setOnChangeListener(this);
		
		depthNumberPicker.setRange(0, Math.round(40*
				DivingMenu.getMetricTypes().get(DivingMenu.getSelectedMetricType())
				.getRatio()));
		timeNumberPicker.setRange(0, 219);
		
		depthNumberPicker.setCurrent(1);
		timeNumberPicker.setCurrent(1);
		
		depth = 1;
		time = 1;
		
		LevelIndicator.IndicateLevel(topLayout, DivingMenu.getCurrentNitroLevel());
		
		prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		boolean remindMeasure = prefs.getBoolean("remindMeasure", true);
		
		if ( remindMeasure )
		{
			final View view = depthNumberPicker.findViewById(R.id.TagImageView);
			final Activity context = this;
			
			view.post( new Runnable() {
		        public void run() {		
		        	
		        	int[] location = new int[2];
		        	view.getLocationOnScreen(location);
		        	location[0]+=view.getWidth()/2-18;
		        	location[1]+=view.getHeight()/2+10;
		            
		        	LayoutInflater inflater = (LayoutInflater)context.getSystemService 
		    		(Context.LAYOUT_INFLATER_SERVICE);
		    		
		    		View measureBubble = inflater.inflate(R.layout.measure_helper_bubble, null);
		    		CheckBox knowCheckBox = (CheckBox) measureBubble.findViewById(R.id.IKnowCheckBox);
		    		knowCheckBox.setOnCheckedChangeListener((OnCheckedChangeListener) context);
		        	measureBubble.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		    				        	
		        	PopupWindow window = new PopupWindow(measureBubble,WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);
		        	window.setOutsideTouchable(true);
		        	window.setBackgroundDrawable(new BitmapDrawable());
		        	window.setTouchInterceptor((OnTouchListener) context);
		        	
		        	window.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1]);
		        	popupWindowArray[0] = window;
		        }
		    });
		}
	}

	@Override
	public void onClick(View v) {
		
		timeNumberPicker.clearFocus();
		depthNumberPicker.clearFocus();
		
		switch ( v.getId() )
		{
			case R.id.DiveButton:
			{
				int requiredRestTime;
				
				try
				{
					requiredRestTime = DivingMenu.getmDbHelper().fetchTheRequiredSurfaceTime(
							DivingMenu.getCurrentTableId(), depth, time, 
							DivingMenu.getCurrentNitroLevel());
				}
				catch ( DataNotPresentException e )
				{
					e.printStackTrace();
					
					DatabaseErrorDialogDisplayer.displayErrorDialog(this);
					
					break;
				}
				
				DivingMenu.SetRequiredRestTime(requiredRestTime);
				
				setResult(Activity.RESULT_OK);
				
				finish();
				
				break;
			}
			case R.id.CancelDiveButton:
			{
				setResult(Activity.RESULT_CANCELED);
				
				finish();
				
				break;
			}
			default: break;
		}
	}

	@Override
	public void onChanged(NumberPicker picker, int oldVal, int newVal) {
		switch ( picker.getId())
		{
			case R.id.Depth:
			{
				depth = depthNumberPicker.getCurrentWithSelectedMetric();
				
				break;
			}
			case R.id.Time:
			{
				time = newVal;
				
				break;
			}
			default: 
				break;
		}
	}

	@Override
	public void onMetricChanged(NumberPicker picker, int currentMetricType) {
		if ( picker == depthNumberPicker )
		{
			DivingMenu.setSelectedMetricType(currentMetricType);
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if ( (v != null) && v.equals(popupWindowArray[0]))
		{
			popupWindowArray[0].dismiss();
			return true;
		}
		return false;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		SharedPreferences.Editor editor = prefs.edit();
		editor.putBoolean("remindMeasure", false);
		editor.commit();
		
		//checking for null - just in case
		if ( popupWindowArray[0] != null)
		{
			popupWindowArray[0].dismiss();
		}
	}

}
